package com.crmeb.crmebcollect;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Presentation;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaRouter;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.crmeb.jsbridge.IJsCallBack;
import com.crmeb.jsbridge.JsBridgeApi;
import com.crmeb.jsbridge.JsMessageBean;
import com.crmeb.jsbridge.JsonUtil;
import com.crmeb.jsbridge.NativeJSCallBack;
import com.crmeb.jsbridge.NativeMessageBean;
import com.sunmi.peripheral.printer.InnerPrinterCallback;
import com.sunmi.peripheral.printer.InnerPrinterException;
import com.sunmi.peripheral.printer.InnerPrinterManager;
import com.sunmi.peripheral.printer.SunmiPrinterService;

import java.io.IOException;
import java.io.InputStream;

public class WebViewActivity extends AppCompatActivity {

    // 网页容器
    private WebView webView;

    // js 和 Java 交互
    private JsBridgeApi mJsBridgeApi;

    // 商米 服务
    private SunmiPrinterService sunmiPrinterService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        // web view
        webView = new WebView(this);
        setContentView(webView);

        AssetManager assetManager=this.getAssets(); //获取assets下内容

        // 初始化SunMi
        // 初始化商米驱动
        initSunmiPrinterService(WebViewActivity.this);

        WebSettings webSettings = webView.getSettings();
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setJavaScriptEnabled(true);
        MediaRouter mediaRouter = (MediaRouter) WebViewActivity.this.getSystemService(Context.MEDIA_ROUTER_SERVICE);
        MediaRouter.RouteInfo route = mediaRouter.getDefaultRoute();
        mJsBridgeApi = new JsBridgeApi(webView, new IJsCallBack() {
            @Override
            public void onJsCall(JsMessageBean jsMessageBean) {
                Log.v("onJsCall", JsonUtil.toJsonString(jsMessageBean));
//                Toast.makeText(getApplicationContext(),"js call native "+JsonUtil.toJsonString(jsMessageBean),Toast.LENGTH_SHORT).show();
                // 在此判断js 调用的java 原生方法
                // 打开钱箱
                if(jsMessageBean.method.equals("openCacheBox")){
                    Toast.makeText(getApplicationContext(),"执行打开钱箱操作--》JS --JAVA" + JsonUtil.toJsonString(jsMessageBean),Toast.LENGTH_SHORT).show();
                    openCashBox();
                }
                if(jsMessageBean.method.equals("collectLoginSuccess")){
                    Toast.makeText(getApplicationContext(),"收银员登录成功--》JS --JAVA" + JsonUtil.toJsonString(jsMessageBean),Toast.LENGTH_SHORT).show();
                    // 顾显操作
//                    if (route != null) {
                        Display presentationDisplay = route.getPresentationDisplay();
                        if (presentationDisplay != null) {
                            Presentation presentation = new MyPresentation(WebViewActivity.this, presentationDisplay);
                            webView = new WebView(WebViewActivity.this);
                            presentation.setContentView(webView);
                            webView.setWebChromeClient(new WebChromeClient());
                            webView.setWebViewClient(new WebViewClient());
                            webView.loadUrl("file:///android_asset/presentation.html");
                            presentation.show();
                        }
//                    }
                }
                // 收银员注销后关闭顾显 业务数据显示
                if(jsMessageBean.method.equals("collectLogout")){
                    Toast.makeText(getApplicationContext(),"收银员登出成功--》JS --JAVA" + JsonUtil.toJsonString(jsMessageBean),Toast.LENGTH_SHORT).show();
                    Display presentationDisplay = route.getPresentationDisplay();
                    Presentation presentation = new MyPresentation(WebViewActivity.this, presentationDisplay);
                    ImageView iv = new ImageView(WebViewActivity.this);
                    try {
                        InputStream inputStream = assetManager.open("gx.jpeg");
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        iv.setImageBitmap(bitmap);
                        presentation.setContentView(iv);
                        presentation.show();
                    }  catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                mJsBridgeApi.notifyNativeTaskFinished("sf", jsMessageBean.id);
            }
        });
        mJsBridgeApi.openJsBridgeChannel(webView);
        WebView.setWebContentsDebuggingEnabled(true);
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (webView.canGoBack()) {
                    webView.goBack();
                    return true;
                } else {
                    return false;
                }
            }
        });
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("file:///android_asset/main.html");
//        webView.loadUrl("https://test.pro.wuht.net/cashier/cashier/index");

//        WebSettings webSettings = webView.getSettings();
//        // 让WebView能够执行javaScript
//        webSettings.setJavaScriptEnabled(true);
//        // 让JavaScript可以自动打开windows
//        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//        // 设置缓存
//        webSettings.setAppCacheEnabled(true);
//        // 设置缓存模式,一共有四种模式
//        webSettings.setCacheMode(webSettings.LOAD_DEFAULT);
//        // 设置缓存路径
////        webSettings.setAppCachePath("");
//        // 支持缩放(适配到当前屏幕)
//        webSettings.setSupportZoom(true);
//        // 将图片调整到合适的大小
//        webSettings.setUseWideViewPort(true);
//        // 支持内容重新布局,一共有四种方式
//        // 默认的是NARROW_COLUMNS
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        // 设置可以被显示的屏幕控制
//        webSettings.setDisplayZoomControls(true);
//        // 设置默认字体大小
//        webSettings.setDefaultFontSize(12);
//        // 开启Storege
//        webSettings.setDomStorageEnabled(Boolean.TRUE);
//        // 开启本地存储
//        webSettings.setDatabaseEnabled(Boolean.TRUE);





    }


    /////////////////////////////////////////////////// For SUNMI START

    private final InnerPrinterCallback innerPrinterCallback = new InnerPrinterCallback() {
        @Override
        protected void onConnected(SunmiPrinterService service) {
            sunmiPrinterService = service;
//            checkSunmiPrinterService(service);
        }

        @Override
        protected void onDisconnected() {
            sunmiPrinterService = null;
//            sunmiPrinter = LostSunmiPrinter;
        }
    };

    /**
     * init sunmi print service
     */
    public void initSunmiPrinterService(Context context){
        try {
            boolean ret =  InnerPrinterManager.getInstance().bindService(context,
                    innerPrinterCallback);
            if(!ret){
//                sunmiPrinter = NoSunmiPrinter;
                Toast.makeText(WebViewActivity.this, "初始化钱箱服务失败", Toast.LENGTH_LONG).show();
            }
        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
    }



    public void openCashBox(){
        if(sunmiPrinterService == null){
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.openDrawer(null);
        } catch (RemoteException e) {
            Toast.makeText(WebViewActivity.this,"Exception:"+e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }

    /////////////////////////////////////////////////// For SUNMI END
}